<script lang="ts" setup>
import {queryVideoState} from '@/api/video'
import navigateTo from '@/utils/navigator'

const {isLogin} = $(useUser())
const {videoInfo, videoChapterList, toPlayer} = $(useVideo())

// 显示购买还是观看按钮
let payOrPlay = $ref<boolean>(false)

// 请求课程是否购买接口
onLoad(async (query) => {
    if (!isLogin) return
    payOrPlay = (await queryVideoState(Number(query!.id))).code === 0
})

// 定位or粘性定位
let canScroll = $ref(false)

let lock = false
let timer: number

// 根据监听是否可以滑动改变bottom样式
uni.$on('canScrollDetails', (isCanScroll) => {
    if (!lock) {
        canScroll = isCanScroll
        lock = true
    } else {
        timer && clearTimeout(timer)
        timer = setTimeout(() => {
            canScroll = isCanScroll
            lock = false
        }, 100)
    }
})

// 去播放或者支付页面
async function toPayOrPlay() {
    if (!payOrPlay) {
        toPayPage()
    } else toPlayPage()
}

// 跳转播放页面
function toPlayPage() {
    navigateTo(`/pages/player/index?id=${videoInfo!.id}&eid=${videoChapterList[0].episodeList[0].id}`)
}

// 跳转播放页面
function toPayPage() {
    navigateTo(`/pages/pay/index?id=${videoInfo!.id}`)
}

</script>

<template>
    <view style="box-shadow: 0px 3px 10px 0px rgba(215, 215, 215, 0.35)"
          class="bottom-0 flex items-center h-100 bg-white w-full box-border px-9"
          :class="[payOrPlay ? 'center' : 'justify-between', canScroll ? 'sticky' : 'absolute']">
        <view v-if="!payOrPlay" center flex-col @click="toPlayer(videoChapterList[0].episodeList[0])">
            <image w-50 h-50 src="@/static/images/icons/video/detail/play_black.png"/>
            <text text="20 #707070">
                试看
            </text>
        </view>
        <view flex>
            <button rounded-full h-70 w-500 center bg="#4d555d" text="30 white" @click="toPayOrPlay">
                {{ payOrPlay ? '立即播放' : '单独购买' }}
            </button>
        </view>
    </view>
</template>
